package com.ocp.macro.handler;

import com.ocp.macro.enums.DataCode;
import com.ocp.macro.utils.ResultInfoUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class LoginFailedHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        Map<String, Object> map = new HashMap<>();
        log.error("登录失败：{}", e.toString());
        if (e instanceof UsernameNotFoundException || e instanceof BadCredentialsException) { // 账号不存在
            map.put("code", DataCode.ACCOUNT_LOGIN_FAIL.getCode());
            map.put("message", DataCode.ACCOUNT_LOGIN_FAIL.getMessage());
        } else if (e instanceof DisabledException) { // 账号被禁用
            map.put("code", DataCode.ACCOUNT_DISABLE.getCode());
            map.put("message", DataCode.ACCOUNT_DISABLE.getMessage());
        } else {
            map.put("code", DataCode.FAIL.getCode());
            map.put("message", DataCode.FAIL.getMessage());
        }

        ResultInfoUtils.responseData(httpServletResponse, map);
    }
}
